package com.mb.app.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.mb.app.domain.*;
import com.mb.app.dao.TbProductInfoMapper;
import com.mb.app.service.*;
import com.mb.common.config.CommonConfig;
import com.mb.solr.bo.SolrProductBO;
import com.mb.solr.service.ISolrService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 商品信息  服务实现类
 * </p>
 *
 * @author liliping
 * @since 2019-04-02
 */
@Service
@Slf4j
public class TbProductInfoServiceImpl extends ServiceImpl<TbProductInfoMapper, TbProductInfo> implements ITbProductInfoService {

    @Autowired
    private CommonConfig commonConfig;

    @Autowired
    private ITbProductColorService productColorService;

    @Autowired
    private ITbProductSpecsService productSpecsService;

    @Autowired
    private ITbProductPriceService productPriceService;

    @Autowired
    private ITbProductPicService productPicService;

    @Autowired
    private ITbShipFeeCfgService shipFeeCfgService;

    @Autowired
    private ITbProductShipFeeCfgService productShipFeeCfgService;

    @Autowired
    private ISolrService solrService;
    @Override
    public List<TbProductInfo> queryList(Map<String, Object> map) {
        List<TbProductInfo> list = this.baseMapper.lst(map);
        return list;
    }

    @Override
    public int count(Map<String, Object> map) {
        return this.baseMapper.countt(map);
    }

    @Override
    public int save(TbProductInfo tbProductInfo, String[] colorIds, String[] specsIds) {
        tbProductInfo.setCreateTime(new Date());
        if (StringUtils.isNotEmpty(tbProductInfo.getFrontPicUrl())) {
            String FrontPicUrl = tbProductInfo.getFrontPicUrl();
            FrontPicUrl = FrontPicUrl.replaceAll(commonConfig.getImgDomain(), "");
            tbProductInfo.setFrontPicUrl(FrontPicUrl);
        }
        int istre = this.baseMapper.insertSelective(tbProductInfo);

        // 添加主图
        this.insertMainPic(tbProductInfo);

        // 判断是否上传了视频
        if (tbProductInfo.getPicType() == 2) {
            // 添加商品图片图片
            this.insertPic(tbProductInfo);
        }
        if (colorIds != null && colorIds.length > 0 && specsIds != null && specsIds.length > 0) {
            List<Long> productColorList = new ArrayList<Long>();
            for (int i = 0; i < colorIds.length;i++) {
                // 添加商品颜色
                TbProductColor productColor = new TbProductColor();
                productColor.setAddUserId(tbProductInfo.getAddUserId());
                productColor.setCreateTime(new Date());
                productColor.setProductId(tbProductInfo.getProductId());
                productColor.setColorId(Long.parseLong(colorIds[i]));
                productColorService.insertSelective(productColor);
                productColorList.add(productColor.getId());
            }
            List<Long> productSpecsList = new ArrayList<Long>();
            for (int j = 0; j < specsIds.length;j++) {
                // 添加商品规格属性
                TbProductSpecs productSpecs = new TbProductSpecs();
                productSpecs.setAddUserId(tbProductInfo.getAddUserId());
                productSpecs.setCreateTime(new Date());
                productSpecs.setProductId(tbProductInfo.getProductId());
                productSpecs.setSpecsId(Long.parseLong(specsIds[j]));
                productSpecsService.insertSelective(productSpecs);
                productSpecsList.add(productSpecs.getId());
            }
            for (int t = 0; t < productColorList.size(); t++) {
                for (int s1 = 0; s1 < productSpecsList.size();s1++) {
                    // 添加商品价格
                    TbProductPrice productPrice = new TbProductPrice();
                    productPrice.setAddUserId(tbProductInfo.getAddUserId());
                    productPrice.setCreateTime(new Date());
                    productPrice.setProductId(tbProductInfo.getProductId());
                    productPrice.setColorId(productColorList.get(t));
                    productPrice.setSpecsId(productSpecsList.get(s1));
                    productPrice.setPrice(tbProductInfo.getPrice());
                    productPrice.setStock(9999);
                    productPriceService.insertSelective(productPrice);
                }
            }
            for (int s = 0; s < colorIds.length; s++) {
                // 添加商品图片信息
                TbProductPic productPic = new TbProductPic();
                productPic.setAddUserId(tbProductInfo.getAddUserId());
                productPic.setCreateTime(new Date());
                productPic.setProductId(tbProductInfo.getProductId());
                productPic.setColorId(productColorList.get(s));
                productPicService.insertSelective(productPic);
            }
        }
        // 添加商品运费配置
        Map<String,Object> shipFeeMap = new HashMap<String, Object>();
        List<TbShipFeeCfg> shipFeeCfgs = shipFeeCfgService.queryList(shipFeeMap);
        if(shipFeeCfgs.size() > 0) {
            for(int i = 0; i < shipFeeCfgs.size(); i++) {
                TbShipFeeCfg tbShipFeeCfg = shipFeeCfgs.get(i);
                TbProductShipFeeCfg productShipFeeCfg = new TbProductShipFeeCfg();
                productShipFeeCfg.setAreaIds(tbShipFeeCfg.getAreaIds());
                productShipFeeCfg.setFirstAmt(tbShipFeeCfg.getFirstAmt());
                productShipFeeCfg.setFirstNums(tbShipFeeCfg.getFirstNums());
                productShipFeeCfg.setSecondAmt(tbShipFeeCfg.getSecondAmt());
                productShipFeeCfg.setSecondNums(tbShipFeeCfg.getSecondNums());
                productShipFeeCfg.setProductId(tbProductInfo.getProductId());
                productShipFeeCfgService.insert(productShipFeeCfg);
            }
        }

        // 修改solr
        this.solrUpdate(tbProductInfo);
        return istre;
    }

    @Override
    public int remove(Long productId, Long delUserId) {
//        return this.baseMapper.deleteById(appId);
        TbProductInfo TbProductInfo = new TbProductInfo();
        TbProductInfo.setProductId(productId);
        TbProductInfo.setDeleteTime(new Date());
        TbProductInfo.setDataStatus(0);
        TbProductInfo.setDeleteUserId(delUserId);
        int istre = this.baseMapper.updateById(TbProductInfo);
        solrService.deleteProduct(TbProductInfo.getProductId());
        return istre;
    }

    @Override
    public TbProductInfo getDtl(Long productId) {
        TbProductInfo TbProductInfo = this.baseMapper.selectByIds(productId);
        if (TbProductInfo != null && StringUtils.isNotEmpty(TbProductInfo.getFrontPicUrl())) {
            TbProductInfo.setFrontPicUrl(commonConfig.getImgDomain() + TbProductInfo.getFrontPicUrl());
        }
        if (TbProductInfo != null && StringUtils.isNotEmpty(TbProductInfo.getPicUrl())) {
            TbProductInfo.setPicUrl(commonConfig.getImgDomain() + TbProductInfo.getPicUrl());
        }
        if (TbProductInfo != null && StringUtils.isNotEmpty(TbProductInfo.getVideoUrl())) {
            TbProductInfo.setVideoUrl(commonConfig.getImgDomain() + TbProductInfo.getVideoUrl());
        }
        Map<String,Object> picMap = new HashMap<String, Object>();
        picMap.put("product_id",TbProductInfo.getProductId());
        picMap.put("pic_type",2);
        picMap.put("data_status",1);
        List<TbProductPic> pics =  productPicService.selectByMap(picMap);
        if (pics.size()>0) {
            TbProductInfo.setPicType(2);
        }else {
            TbProductInfo.setPicType(1);
        }
        // 增加额外主图
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("product_id",TbProductInfo.getProductId());
        map.put("color_id",0);
        map.put("pic_type",1);
        map.put("data_status",1);
        List<TbProductPic> productPics = productPicService.selectByMap(map);
        if (productPics != null && productPics.size() == 3) {
            for (int i = 0; i < productPics.size(); i++) {
                TbProductPic productPic = productPics.get(i);
                if (i == 0) {
                    if (StringUtils.isNotEmpty(productPic.getPicUrl())) {
                        TbProductInfo.setFrontPicUrl(commonConfig.getImgDomain()+productPic.getPicUrl());
                    }
                }else if (i == 1) {
                    if (StringUtils.isNotEmpty(productPic.getPicUrl())) {
                        TbProductInfo.setFrontPicUrlOne(commonConfig.getImgDomain()+productPic.getPicUrl());
                    }
                }else if (i == 2) {
                    if (StringUtils.isNotEmpty(productPic.getPicUrl())) {
                        TbProductInfo.setFrontPicUrlTwo(commonConfig.getImgDomain()+productPic.getPicUrl());
                    }
                }
            }
        }
        return TbProductInfo;
    }

    @Override
    public boolean productInfoNameExit(Map<String, Object> params) {
        boolean exit;
        exit = this.baseMapper.selectByProductInfo(params).size() > 0;
        return exit;
    }

    @Override
    public int status(Long productId, Integer productStatus) {
        TbProductInfo tbProductInfo = new TbProductInfo();
        tbProductInfo.setProductId(productId);
        tbProductInfo.setProductStatus(productStatus);
        int istre = this.baseMapper.updateById(tbProductInfo);
        if (productStatus == 0) {
            solrService.deleteProduct(productId);
        }else if (productStatus == 1){
            TbProductInfo productInfo = this.baseMapper.selectById(productId);
            // 修改solr
            this.solrUpdate(productInfo);
        }
        return istre;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(TbProductInfo TbProductInfo, String[] colorIds, String[] specsIds) {
        TbProductInfo.setUpdateTime(new Date());
        if (StringUtils.isNotEmpty(TbProductInfo.getFrontPicUrl())) {
            String FrontPicUrl = TbProductInfo.getFrontPicUrl();
            FrontPicUrl = FrontPicUrl.replaceAll(commonConfig.getImgDomain(), "");
            TbProductInfo.setFrontPicUrl(FrontPicUrl);
        }
        int istre = this.baseMapper.updateById(TbProductInfo);

        //修改主图
        this.updateMainPic(TbProductInfo);

        // 先清除商品视频图片,判断是否上传视频,添加商品图片
        this.deleteProductVideo(TbProductInfo);

        // 判断颜色(colorIds)，规格(specsIds)是否为空
        if (colorIds != null && colorIds.length > 0 && specsIds != null && specsIds.length > 0) {
            // 删除产品颜色
            this.deleteProductColorSpecs(colorIds, TbProductInfo.getProductId(), 1);

            for (int i = 0; i < colorIds.length; i++) {
                // 根据商品id 和 颜色属性配置表id 查询商品颜色表
                Map<String, Object> colorMap = new HashMap<String, Object>();
                colorMap.put("product_id", TbProductInfo.getProductId());
                colorMap.put("color_id", Long.parseLong(colorIds[i]));
                TbProductColor productColorList = productColorService.selectByProductColor(colorMap);
                // 判断商品颜色表有没有此记录 如果有则不改变 没有添加一条
                if (productColorList == null) {
                    TbProductColor productColor = new TbProductColor();
                    productColor.setAddUserId(TbProductInfo.getAddUserId());
                    productColor.setCreateTime(new Date());
                    productColor.setProductId(TbProductInfo.getProductId());
                    productColor.setColorId(Long.parseLong(colorIds[i]));
                    productColorService.insertSelective(productColor);
                }
            }
            // 删除产品规格
            this.deleteProductColorSpecs(specsIds, TbProductInfo.getProductId(), 2);

            for (int i = 0; i < specsIds.length; i++) {
                // 根据商品id 和 规格属性配置表id 查询商品规格表
                Map<String, Object> colorMap = new HashMap<String, Object>();
                colorMap.put("product_id", TbProductInfo.getProductId());
                colorMap.put("specs_id", Long.parseLong(specsIds[i]));
                TbProductSpecs productSpecsList = productSpecsService.selectByProductSpecs(colorMap);
                // 判断商品规格表有没有此记录 如果有则不改变 没有添加一条
                if (productSpecsList == null) {
                    // 添加商品规格属性
                    TbProductSpecs productSpecs = new TbProductSpecs();
                    productSpecs.setAddUserId(TbProductInfo.getAddUserId());
                    productSpecs.setCreateTime(new Date());
                    productSpecs.setProductId(TbProductInfo.getProductId());
                    productSpecs.setSpecsId(Long.parseLong(specsIds[i]));
                    productSpecsService.insertSelective(productSpecs);
                }
            }
            // 添加商品价格
            Map<String, Object> objectMap = new HashMap<String, Object>();
            objectMap.put("product_id", TbProductInfo.getProductId());
            List<TbProductColor> productColorList = productColorService.getProductColorList(objectMap);
            List<TbProductSpecs> productSpecsList = productSpecsService.getProductSpecsList(objectMap);
            if (productColorList.size() > 0 && productSpecsList.size() > 0) {
                for (int i = 0; i < productColorList.size(); i++) {
                    for (int j = 0; j < productSpecsList.size(); j++) {
                        // 查询商品价格
                        Map<String,Object> priceMap = new HashMap<String, Object>();
                        priceMap.put("product_id",TbProductInfo.getProductId());
                        priceMap.put("color_id",productColorList.get(i).getId());
                        priceMap.put("specs_id",productSpecsList.get(j).getId());
                        TbProductPrice productPrice = productPriceService.selectByIds(priceMap);
                        if (productPrice == null) {
                            // 添加商品价格
                            TbProductPrice price = new TbProductPrice();
                            price.setAddUserId(TbProductInfo.getAddUserId());
                            price.setCreateTime(new Date());
                            price.setProductId(TbProductInfo.getProductId());
                            price.setColorId(productColorList.get(i).getId());
                            price.setSpecsId(productSpecsList.get(j).getId());
                            price.setPrice(TbProductInfo.getPrice());
                            productPriceService.insertSelective(price);
                        }
                    }
                }

            }
            // 添加商品颜色图片
            if (productColorList.size() > 0) {
                for (int i = 0; i < productColorList.size(); i++) {
                    TbProductPic tbProductPic = this.selectPic(TbProductInfo.getProductId(),productColorList.get(i).getId());
                    if (tbProductPic == null) {
                        // 添加商品图片信息
                        this.insertPic(TbProductInfo,productColorList.get(i).getId());
                    }
                }
            }
            // 修改solr
            this.solrUpdate(TbProductInfo);
        }
        return istre;
    }

    public void deleteProductVideo(TbProductInfo tbProductInfo) {
        // 清除商品视频图片
        Map<String, Object> picMap = new HashMap<String, Object>();
        picMap.put("product_id", tbProductInfo.getProductId());
        picMap.put("pic_type", 2);
        picMap.put("data_status", 1);
        List<TbProductPic> pics = productPicService.selectByMap(picMap);
        if (pics.size() > 0) {
            for (int i = 0; i < pics.size(); i++) {
                TbProductPic tbProductPic1 = pics.get(i);
                TbProductPic productPic = new TbProductPic();
                productPic.setId(tbProductPic1.getId());
                productPic.setDataStatus(0);
                productPicService.update(productPic);
            }
        }
        // 判断是否上传了视频
        if (tbProductInfo.getPicType() == 2) {
            // 添加商品图片图片
            this.insertPic(tbProductInfo);
        }
    }

    public void insertPic(TbProductInfo tbProductInfo) {
        // 添加商品图片图片
        TbProductPic productPic = new TbProductPic();
        productPic.setAddUserId(tbProductInfo.getAddUserId());
        productPic.setCreateTime(new Date());
        if (StringUtils.isNotEmpty(tbProductInfo.getFrontPicUrl())) {
            String picUrl = tbProductInfo.getFrontPicUrl();
            picUrl = picUrl.replaceAll(commonConfig.getImgDomain(), "");
            productPic.setPicUrl(picUrl);
        }
        productPic.setPicType(2);
        if (StringUtils.isNotEmpty(tbProductInfo.getVideoUrl())) {
            String VideoUrl = tbProductInfo.getVideoUrl();
            VideoUrl = VideoUrl.replaceAll(commonConfig.getImgDomain(), "");
            productPic.setVideoUrl(VideoUrl);
        }
        productPic.setProductId(tbProductInfo.getProductId());
        productPicService.insertSelective(productPic);
    }

    public void insertPic(TbProductInfo productInfo,Long colorId) {
        // 添加商品图片信息
        TbProductPic productPic = new TbProductPic();
        productPic.setAddUserId(productInfo.getAddUserId());
        productPic.setCreateTime(new Date());
        productPic.setProductId(productInfo.getProductId());
        productPic.setColorId(colorId);
        productPicService.insertSelective(productPic);
    }

    public  void  deletePrice(Long productId,Long id,int type) {
        TbProductPrice productPrice = new TbProductPrice();
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("product_id",productId);
        map.put("data_status",1);
        if (type == 1) {
            map.put("color_id",id);
        }else if (type == 2){
            map.put("specs_id",id);
        }
        List<TbProductPrice> productPrices = productPriceService.selectByMap(map);
        if (productPrices.size() > 0) {
            for (int i =0; i < productPrices.size(); i++) {
                TbProductPrice productPrice1 = new TbProductPrice();
                productPrice1.setId(productPrices.get(i).getId());
                productPrice1.setDataStatus(0);
                productPriceService.updateById(productPrice1);
            }
        }
    }


    // 删除颜色、规格
    public void deleteProductColorSpecs(String[] Ids, Long prodcutId, int type) {
        Map<String, Object> colMap = new HashMap<>();
        colMap.put("product_id", prodcutId);
        colMap.put("list", Ids);
        if (type == 1) { //  colorIds
            List<TbProductColor> tbProductColors = productColorService.getProductColorList(colMap);
            if (tbProductColors.size() > 0) {
                for (int i = 0; i < tbProductColors.size(); i++) {
                    TbProductColor tbProductColor = tbProductColors.get(i);
                    TbProductColor productColor = new TbProductColor();
                    productColor.setId(tbProductColor.getId());
                    productColor.setDataStatus(0);
                    productColorService.updateById(productColor);
                    // 删除价格表
                    this.deletePrice(prodcutId,tbProductColor.getId(),1);
                    // 删除商品图片表
                    this.deletePic(prodcutId,tbProductColor.getId());
                }
            }
        } else if (type == 2) { //specsIds
            List<TbProductSpecs> tbProductSpecs = productSpecsService.getProductSpecsList(colMap);
            if (tbProductSpecs.size() > 0) {
                for (int i = 0; i < tbProductSpecs.size(); i++) {
                    TbProductSpecs productSpecs = tbProductSpecs.get(i);
                    TbProductSpecs productSpecs1 = new TbProductSpecs();
                    productSpecs1.setId(productSpecs.getId());
                    productSpecs1.setDataStatus(0);
                    productSpecsService.updateById(productSpecs1);
                    // 删除价格表
                    this.deletePrice(prodcutId,productSpecs.getId(),2);
                }
            }
        }
    }

    public TbProductPic selectPic(Long productId,Long colorId) {
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("product_id",productId);
        map.put("data_status",1);
        map.put("pic_type",1);
        map.put("color_id",colorId);
        TbProductPic productPic = new TbProductPic();
        productPic.setProductId(productId);
        productPic.setDataStatus(1);
        productPic.setPicType(1);
        productPic.setColorId(colorId);
        TbProductPic productPics = null;
        try {
            productPics = productPicService.selectByIds(productPic);
        } catch (Exception e) {
            log.info("productPics Exception",e);
        }
        return productPics;
    }

    public void deletePic(Long productId,Long colorId) {
        TbProductPic pic = this.selectPic(productId,colorId);
        if (pic !=  null) {
            TbProductPic productPic = new TbProductPic();
            productPic.setId(pic.getId());
            productPic.setDataStatus(0);
            productPicService.update(productPic);
        }
    }


    public void insertMainPic(TbProductInfo productInfo){
        // 添加商品图片图片
        TbProductPic productPic = new TbProductPic();
        productPic.setProductId(productInfo.getProductId());
        productPic.setAddUserId(productInfo.getAddUserId());
        productPic.setColorId((long)0);
        productPic.setCreateTime(new Date());
        productPic.setPicType(1);
        if (StringUtils.isNotEmpty(productInfo.getFrontPicUrl())) {
            String picUrl = productInfo.getFrontPicUrl();
            picUrl = picUrl.replaceAll(commonConfig.getImgDomain(), "");
            productPic.setPicUrl(picUrl);
        }
        productPicService.insertSelective(productPic);
        if (StringUtils.isNotEmpty(productInfo.getFrontPicUrlOne())) {
            String picUrl = productInfo.getFrontPicUrlOne();
            picUrl = picUrl.replaceAll(commonConfig.getImgDomain(), "");
            productPic.setPicUrl(picUrl);
        }
        productPicService.insertSelective(productPic);
        if (StringUtils.isNotEmpty(productInfo.getFrontPicUrlTwo())) {
            String picUrl = productInfo.getFrontPicUrlTwo();
            picUrl = picUrl.replaceAll(commonConfig.getImgDomain(), "");
            productPic.setPicUrl(picUrl);
        }
        productPicService.insertSelective(productPic);
    }

    public void updateMainPic(TbProductInfo productInfo) {
        // 修改商品主图图片
        //查询 主图
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("product_id",productInfo.getProductId());
        map.put("color_id",0);
        map.put("pic_type",1);
        map.put("data_status",1);
        List<TbProductPic> productPics = productPicService.selectByMap(map);
        if (productPics != null && productPics.size() == 3) {
            for (int i = 0; i < productPics.size();i++) {
                TbProductPic pic = productPics.get(i);
                TbProductPic productPic = new TbProductPic();
                productPic.setProductId(productInfo.getProductId());
                productPic.setUpdateUserId(productInfo.getUpdateUserId());
                productPic.setId(pic.getId());
                if (i == 0) {
                    if (StringUtils.isNotEmpty(productInfo.getFrontPicUrl())) {
                        String picUrl = productInfo.getFrontPicUrl();
                        picUrl = picUrl.replaceAll(commonConfig.getImgDomain(), "");
                        productPic.setPicUrl(picUrl);
                    }
                }else if (i == 1) {
                    if (StringUtils.isNotEmpty(productInfo.getFrontPicUrlOne())) {
                        String picUrl = productInfo.getFrontPicUrlOne();
                        picUrl = picUrl.replaceAll(commonConfig.getImgDomain(), "");
                        productPic.setPicUrl(picUrl);
                    }
                }else if (i == 2) {
                    if (StringUtils.isNotEmpty(productInfo.getFrontPicUrlTwo())) {
                        String picUrl = productInfo.getFrontPicUrlTwo();
                        picUrl = picUrl.replaceAll(commonConfig.getImgDomain(), "");
                        productPic.setPicUrl(picUrl);
                    }
                }
                productPicService.update(productPic);
            }
        }
    }


    public void solrUpdate(TbProductInfo tbProductInfo){
        // 查询颜色 规格 名称
        // 根据 productId 查询 颜色规格
        Map<String, Object> Map = new HashMap<String, Object>();
        Map.put("product_id", tbProductInfo.getProductId());
        List<TbProductColor> productColorList = productColorService.getProductColorList(Map);
        List<TbProductSpecs> productSpecsList = productSpecsService.getProductSpecsList(Map);
        String[] color = null;
        if (productColorList.size() > 0) {
            color = new String[productColorList.size()];
            for (int i = 0; i < productColorList.size(); i++) {
                TbProductColor productColor = productColorList.get(i);
                color[i] = productColor.getColorName();
            }
        }
        String[] specs = null;
        if (productSpecsList.size() > 0) {
            specs = new String[productSpecsList.size()];
            for (int i = 0; i < productSpecsList.size(); i++) {
                TbProductSpecs productSpecs = productSpecsList.get(i);
                specs[i] = productSpecs.getSpecsName();
            }
        }
        SolrProductBO productBO = new SolrProductBO();
        productBO.setProductId(tbProductInfo.getProductId());
        productBO.setProductName(tbProductInfo.getProductName());
        productBO.setProductDesc(tbProductInfo.getProductDesc());
        productBO.setColorArr(color);
        productBO.setSpecsArr(specs);
        productBO.setId(tbProductInfo.getProductId().toString());
        solrService.updateProduct(productBO);
    }
}
